<template>
  <div :class="className" :style="{height:height,width:width}" ref="chartRef" />
</template>

<script setup>
import * as echarts from 'echarts'
import 'echarts/theme/macarons'
import useResize from '@/components/Echarts/Composable/resize'

const props = defineProps({
  className: {
    type: String,
    default: 'chart'
  },
  width: {
    type: String,
    default: '200px'
  },
  height: {
    type: String,
    default: '200px'
  },
  name: {
    type: String,
    default: ''
  },
  chartData: {
    type: Array,
    required: true
  },
  colors: {
    type: Array,
    default: () => []
  },
  lineWidth: {
    type: Number,
    default: 14
  },
  offsetCenter: {
    type: Array,
    default: () => ['0%', '0%']
  },
  valueFontSize: {
    type: Number,
    default: 28
  },
  titleFontSize: {
    type: Number,
    default: 14
  }
})

const chartRef = ref(null)
const chart = shallowRef(null)

// 引入 resize 混入
useResize(chart)

// 获取图表数据
const getChartData = (chartData) => {
  const data = []
  chartData.forEach((item, idx) => {
    data.push({
      value: item.value,
      itemStyle: {
        normal: {color: props.colors[idx]}
      }
    })
  })
  return data
}

// 设置图表选项
const setOptions = (chartData) => {
  chart.value.setOption({
    graphic: {
      type: 'text',
      left: 'center',
      top: 'center',
      style: {
        text: '66%', // 文字内容
        fill: '#fff', // 文字颜色
        fontSize: 50 // 文字字号
      }
    },
    series: [
      {
        type: 'pie',
        radius: ['55%', '70%'],
        center: ['50%', '50%'],
        // 隐藏指示线
        labelLine: {show: false},
        data: getChartData(chartData)
      }
    ]
  })
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  chart.value = echarts.init(chartRef.value)
  setOptions(props.chartData)
}

// 监听数据变化
watch(() => props.chartData, (newVal) => {
  setOptions(newVal)
}, {deep: true})

// 生命周期钩子
onMounted(() => {
  nextTick(() => {
    initChart()
  })
})

onBeforeUnmount(() => {
  if (!chart.value) {
    return
  }
  chart.value.dispose()
  chart.value = null
})
</script>
